package com.demo.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;

import com.demo.R;
import com.demo.service.PlacesService;
import com.demo.ui.fragment.PlacesListFragment;
import com.demo.ui.fragment.PlacesMapFragment;

public class MainActivity extends FragmentActivity {

	private boolean DUAL_MODE;
	private Fragment actualFragment;
	private PlacesListFragment listFragment;
	private PlacesMapFragment mapFragment;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Si no encontramos el segundo frame, és que estamos en modo mobil
		// Si lo encontramos, estamos en modo tablet
		DUAL_MODE = findViewById(R.id.frame_map) != null;

		listFragment = new PlacesListFragment();
		mapFragment = new PlacesMapFragment();

		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

		if (!DUAL_MODE) {
			actualFragment = listFragment;
			ft.replace(R.id.frame, listFragment);
		} else {
			ft.replace(R.id.frame_list, listFragment);
			ft.replace(R.id.frame_map, mapFragment);
		}

		ft.commit();
		
		Intent service = new Intent(this, PlacesService.class);
		startService(service);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (!DUAL_MODE) {
			getMenuInflater().inflate(R.menu.main_phone, menu);
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		switch (item.getItemId()) {
		case R.id.action_change_frag:
			if (!DUAL_MODE) {
				FragmentTransaction ft = getSupportFragmentManager()
						.beginTransaction();
				
				if (actualFragment instanceof PlacesListFragment) {
					ft.replace(R.id.frame, mapFragment);
					actualFragment = mapFragment;
				} else {
					ft.replace(R.id.frame, listFragment);
					actualFragment = listFragment;
				}
				ft.commit();
			}
			break;
		}

		return true;
	}

}
